package com.tpshion.deploy.task.support;

import com.tpshion.deploy.util.AssertUtil;
import jakarta.annotation.Resource;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class TaskManager {

    private final Map<String, TaskRunnable> taskMap = new ConcurrentHashMap<>();

    @Resource
    private ThreadPoolTaskExecutor taskExecutor;

    @Resource
    private TaskFactory taskFactory;

    public void removeTask(String taskId){
        TaskRunnable taskRunnable = taskMap.get(taskId);
        if(Objects.isNull(taskRunnable)){
            return;
        }
        taskRunnable.stop();
        taskMap.remove(taskId);
    }

    public void startTask(TaskContext taskContext){
        AssertUtil.isEmpty(taskContext, "任务参数不能为空");
        AssertUtil.isBlank(taskContext.getTaskId(), "任务id不能为空");
        AssertUtil.isEmpty(taskContext.getList(), "任务数据不能为空");
        String taskId = taskContext.getTaskId();
        TaskRunnable taskRunnable = new TaskRunnable(taskContext, taskFactory);
        taskMap.put(taskId, taskRunnable);
        taskExecutor.submit(taskRunnable);
    }
}
